<?php
namespace app\admin\controller\csmitsm;

use think\Db;
use addons\csmitsm\library\xcore\xcore\utils\XcDaoUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcRequestUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcAdminTabUtils;
use addons\csmitsm\library\xcore\xcflow\base\XcformADataCrudBackend;
use addons\csmitsm\library\xcore\xcflow\utils\XcformFieldsUtils;
use addons\csmitsm\library\xcore\xcore\utils\XcDatabaseUtils;

class Xcflowmdmdata extends XcformADataCrudBackend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->assign("statusList", ['normal' => __('Normal'), 'hidden' => __('Hidden')]);

        $this->xcformDao = new \app\admin\model\csmitsm\Xcflowmdm();
  
        $xcform_id = XcRequestUtils::param("xcform_id");
        if (!empty($xcform_id)) {
            $xcform = XcDaoUtils::getRowById(new \app\admin\model\csmitsm\Xcflowmdm(), $xcform_id);
            $this->assignconfig("xcform", $xcform);
            XcAdminTabUtils::append_control_initialize('xcflowmdm', $xcform_id, __CLASS__, $this->view);
        }
    }


    public function index()
    {
        if ($this->request->isAjax() === false) {
            $isconsole = XcRequestUtils::get("isconsole", false, "N");
            $xcform_id = XcRequestUtils::get("xcform_id");
            $xcflowmdm = XcDaoUtils::getRowById(new \app\admin\model\csmitsm\Xcflowmdm(), $xcform_id);
            $xcfieldjsonObj = XcformFieldsUtils::getXcfieldjsonJsonObjectFromXcform($xcflowmdm);

            $columns = [];
            foreach ($xcfieldjsonObj as $field) {
                if (in_array($field['fieldcode'], ["id", $xcflowmdm->displayfieldcode])) {
                    $columns[] = $field;
                }
            }
            $this->view->assign('isconsole', $isconsole);
            $this->view->assign('xcform_id', $xcform_id);
            $this->view->assign('xcflowmdm', $xcflowmdm);
            $this->assignconfig('noprefixtablename', XcDatabaseUtils::getNoprefixTablename($xcflowmdm->publishtablename));
            $this->assignconfig("xcform_id", $xcform_id);
            $this->assignconfig("columns", $columns);

            return $this->view->fetch();
        } else {
            $xcflowmdmId = XcRequestUtils::get("xcform_id");
            $xcflowmdm = XcDaoUtils::getRowById(new \app\admin\model\csmitsm\Xcflowmdm(), $xcflowmdmId);
            $tablename = $xcflowmdm->publishtablename;
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            [$list, $count] = XcDatabaseUtils::getPageListBySql($tablename, $where, $offset, $limit);
            // $list = Db::table($tablename)->where($where)->select();
            // $count = Db::table($tablename)->where($where)->count();

            $result = ['rows' => $list, 'total' => $count];
            return json($result);
        }
    }
 
}
